#!/usr/bin/python3
# -*- coding:utf-8 -*-
""""
@Author: lijk34925
@Time: 2023/4/20 19:44
@File: DataBaseApp.py
"""
import os

from BladeFerm.Lib.Common import logger, ROOT_PATH
from BladeFerm.databases.DbFactory.basic import DatabaseUtil
from BladeFerm.databases.DbFactory.dameng import DaMengUtil
from BladeFerm.databases.DbFactory.mssql import MssqlJdbcUtil
from BladeFerm.databases.DbFactory.mysql import MysqlUtil, MysqlJdbcUtil
from BladeFerm.databases.DbFactory.oceanbase import OceanBaseUtil
from BladeFerm.databases.DbFactory.oracle import OracleJdbcUtil
from BladeFerm.databases.DbFactory.postgresql import PostgreSqlUtil, PostgresqlJdbcUtil
from BladeFerm.utils.basic_opration import is_chinese


class DataBaseApp:
    def __init__(self):
        self.dba = None
        self.env = 'oracle'
        self.factory = dict()

    @staticmethod
    def __set_driver_path(dbconfig: dict):
        sep = os.path.sep
        jar_dir = os.path.join(ROOT_PATH, 'Tools\\driver')
        if is_chinese(jar_dir):
            logger.error(f'{jar_dir} 驱动路径存在中文，请修改路径！')
        dbconfig['jar_dir_path'] = jar_dir
        os.environ["CLASSPATH"] = jar_dir
        if not os.path.exists(jar_dir):
            logger.error(f'{jar_dir} 路径不存在！')
        else:
            files = os.listdir(jar_dir)
            jar_files = [(jar_dir + sep + file) for file in files]
            dbconfig['jar_files'] = jar_files

    def make_db(self, *args, **dbconfig):
        """
        创建数据库，可以多次调用此方法，创建多个数据库连接。
        Args:
            *args:
            **dbconfig:

        self.dba =s:

        """
        self.__set_driver_path(dbconfig)
        db_type = dbconfig.pop('type')
        self.env = dbconfig.pop('env_name', db_type)
        if db_type == 'oracle':
            self.factory[self.env] = OracleJdbcUtil(*args, **dbconfig)
        elif db_type == 'pymysql':
            self.factory[self.env] = MysqlUtil(*args, **dbconfig)
        elif db_type in ('mysql', 'tdsql'):
            self.factory[self.env] = MysqlJdbcUtil(*args, **dbconfig)
        elif db_type == 'oceanbase':
            self.factory[self.env] = OceanBaseUtil(*args, **dbconfig)
        elif db_type == 'dm':
            self.factory[self.env] = DaMengUtil(*args, **dbconfig)
        elif db_type == 'mssql':
            self.factory[self.env] = MssqlJdbcUtil(*args, **dbconfig)
        elif db_type == 'psycopg2':
            self.factory[self.env] = PostgreSqlUtil(*args, **dbconfig)
        elif db_type == 'postgresql':
            self.factory[self.env] = PostgresqlJdbcUtil(*args, **dbconfig)
        else:
            logger.info(
                f'{db_type}暂不支持，目前支持mysql、oracle、oceanbase、dameng、mssql、postgresql，后续计划添加db2以及nosql相关数据库')
            self.factory['base'] = DatabaseUtil()
        self.dba = self.factory[self.env]

    def get_dba(self, env_name=None):
        if env_name:
            self.env = env_name
            self.dba = self.factory[self.env]
        return self.dba

    @staticmethod
    def parse_database_link(link: str):
        """

        Args:
            link: "type=mysql;ip=10.20.37.217;port=33061;user=root;password=root;SERVICE_NAME=hsamlwl"

        Returns:

        """
        infos = link.split(';')
        db_info = dict()
        for unit in infos:
            k, v = unit.split('=')
            if k == 'port':
                db_info[k] = int(v)
            else:
                db_info[k] = str(v)
        return db_info

    def run_one_sql(self, sql_text, env=None):
        if env:
            self.dba = self.factory[env]
        result = self.dba.exec_sql(sql=sql_text)
        logger.debug(f'\n==>执行:{sql_text} \n==>结果：{result}')
        return result

    def get_run_sql_result(self, sql_lines: list, env=None) -> dict:
        """
        执行sql，并返回结果
        Args:
            sql_lines:

        Returns:
        :param sql_lines:
        :param env:
        """
        if env:
            self.dba = self.factory[env]
        sql_response = dict()
        for index, line in enumerate(sql_lines):
            result = self.dba.exec_sql(sql=line)
            sql_response[index] = result
            logger.debug(f'==>执行No.{index} sql:{line}，\n==>结果为：{result}')
        # logger.debug(f'run_sql_result: {sql_response}')
        return sql_response

    def run_sql(self, sql_texts: list, **dbconfig):
        self.__set_driver_path(dbconfig)
        db_driver = dbconfig.pop('type')
        if db_driver == 'oracle':
            with OracleJdbcUtil(**dbconfig) as self.dba:
                sql_response = self.get_run_sql_result(sql_texts)
        elif db_driver in ('mysql', 'tdsql'):
            with MysqlJdbcUtil(**dbconfig) as self.dba:
                sql_response = self.get_run_sql_result(sql_texts)
        elif db_driver == 'oceanbase':
            with OceanBaseUtil(**dbconfig) as self.dba:
                sql_response = self.get_run_sql_result(sql_texts)
        elif db_driver == 'dameng':
            with DaMengUtil(**dbconfig) as self.dba:
                sql_response = self.get_run_sql_result(sql_texts)
        elif db_driver == 'mssql':
            with MssqlJdbcUtil(**dbconfig) as self.dba:
                sql_response = self.get_run_sql_result(sql_texts)
        elif db_driver == 'postgresql':
            with PostgresqlJdbcUtil(**dbconfig) as self.dba:
                sql_response = self.get_run_sql_result(sql_texts)
        else:
            sql_response = dict()
            logger.error(
                f'{db_driver}暂不支持，目前支持mysql、oracle、oceanbase、dameng、mssql、postgresql，后续计划添加db2以及nosql相关数据库')
        return sql_response

    def close_link(self, env=None):
        if env:
            self.dba = self.factory.get(env)
        self.dba.close_db()